package com.tank.util;

import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import com.tank.common.Dir;

/**
 * TODO
 *
 * @author chenwb
 * @since 2024/1/26 22:45
 */
public class ImageUtils {

    /**
     * 加载图片
     *
     * @param path
     * @return
     */
    public static BufferedImage loadImage(String path) {
        BufferedImage image = null;
        try {
            image = ImageIO.read(new File(new Object() {
                public String getPath() {
                    return this.getClass().getResource(path).getPath();
                }
            }.getPath()));
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (image == null) {
            throw new RuntimeException("图片加载失败");
        }
        return image;
}
    /**
     * 旋转图片
     *
     * @param src
     * @param degrees
     * @return
     */
    public static BufferedImage rotateImage(BufferedImage src, double degrees) {
        // AffineTransform affineTransform = AffineTransform.getRotateInstance(Math.toRadians(degrees), src.getWidth() / 2,
        //     (double) src.getHeight() / 2);
        // BufferedImage rotatedImage = new BufferedImage(src.getWidth(), src.getHeight(), src.getType());
        // Graphics2D g = (Graphics2D) rotatedImage.getGraphics();
        // g.setTransform(affineTransform);
        // g.drawImage(src, 0, 0, null);
        // g.dispose();


        int w = src.getWidth();
        int h = src.getHeight();
        int type = src.getColorModel().getTransparency();
        BufferedImage img;
        Graphics2D graphics2d;
        (graphics2d = (img = new BufferedImage(w, h, type))
            .createGraphics()).setRenderingHint(
            RenderingHints.KEY_INTERPOLATION,
            RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        graphics2d.rotate(Math.toRadians(degrees), w / 2, h / 2);
        graphics2d.drawImage(src, 0, 0, null);
        graphics2d.dispose();
        return img;
    }

    public static BufferedImage getImageByDir(BufferedImage bufferedImage, Dir dir) {
        switch (dir) {
            case UP:
                return bufferedImage;
            case DOWN:
                return rotateImage(bufferedImage, 180);
            case LEFT:
                return rotateImage(bufferedImage, 270);
            case RIGHT:
                return rotateImage(bufferedImage, 90);
            default:
                break;
        }
        return bufferedImage;
    }
}
